package com.hx.vending.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hx.vending.annotation.Authorization;
import com.hx.vending.bean.*;
import com.hx.vending.bean.entity.*;
import com.hx.vending.dao.*;
import com.hx.vending.pay.WXPayUtil;
import com.hx.vending.service.ICustomerService;
import com.hx.vending.service.IGoodsService;
import com.hx.vending.service.IOnlineOrderService;
import com.hx.vending.service.IWXPayService;
import com.hx.vending.util.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/11/26.
 * 商品
 */
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IOnlineOrderService iOnlineOrderService;
    @Autowired
    private FieldMapper fieldMapper;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private TrailsMapper trailsMapper;
    @Autowired
    private OnlineOrderMapper onlineOrderMapper;
    @Autowired
    private GoodsConsumeMapper goodsConsumeMapper;
    @Autowired
    private OrderBuyMapper orderBuyMapper;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private DictMapper dictMapper;
    @Resource
    private MedicineMapper medicineMapper;


    /**
     * 插入商品信息
     * @param goods
     * @return
     */
    public Msg insertGoods(Goods goods, Integer userId){
        if(ToolUtil.isNotEmpty(goods) && ToolUtil.isNotEmpty(userId)){
            if (ToolUtil.isEmpty(goods.getGoodsPrice())) {
                return Msg.fail().add("msg", "商品价格不能为空");
            }
            if (ToolUtil.isEmpty(goods.getGoodsName())) {
                return Msg.fail().add("msg", "商品名称不能为空");
            }
            goods.setGoodsUserId(userId);
            int resultinsert = this.goodsMapper.insertSelective(goods);
            if(0 != resultinsert){
                return Msg.success();
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail().add("msg", "请输入正确信息");
        }
    }


    /**
     * 根据用户id及其他条件查询商品
     * @param userId
     * @param goods
     * @return
     */
    public Msg selectGoodsByUserId(Integer userId, Goods goods, Integer pageNum, Integer pageSize){
        if (ToolUtil.isNotEmpty(userId)) {
            goods.setGoodsUserId(userId);

            PageHelper.startPage(pageNum, pageSize);
            List<Goods> goodsList = this.goodsMapper.selectByExampleState(goods);
            if(null != goodsList){

                PageInfo page = new PageInfo(goodsList, 5);
                return Msg.success().add("pageInfo", page);
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }

    }


    /**
     * 删除商品信息
     * @param goodsId 商品id
     * @return
     */
    public Msg deleteGoods(Integer goodsId){
        if(ToolUtil.isNotEmpty(goodsId)){
            Goods goods = new Goods();
            goods.setGoodsId(goodsId);

            //将图片从阿里云上删除
            Goods selectGoods = this.goodsMapper.selectByPrimaryKeySelective(goods);
            if (ToolUtil.isNotEmpty(selectGoods)) {
                AliyunOSSClientUtil.deleteObject(selectGoods.getGoodsPicture());
            }

            goods.setGoodsStatus("0");
            int resultupdate = this.goodsMapper.updateByPrimaryKeySelective(goods);
            if(0 != resultupdate){
                return Msg.success();
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }


    /**
     * 修改商品信息
     * @param goods
     * @return
     */
    public Msg updateGoods(Goods goods){
        if(ToolUtil.isNotEmpty(goods)){

            int resultupdate = this.goodsMapper.updateByPrimaryKeySelective(goods);
            if(0 != resultupdate){

                //修改商品时从阿里云删除以前的图片
                if (goods.getGoodsPicture() != null) {
                    Goods selectGoods = new Goods();
                    selectGoods.setGoodsId(goods.getGoodsId());
                    Goods selectResultGoods = this.goodsMapper.selectByPrimaryKeySelective(selectGoods);
                    if (ToolUtil.isNotEmpty(selectResultGoods)) {
                        AliyunOSSClientUtil.deleteObject(selectResultGoods.getGoodsPicture());
                    }
                }

                return Msg.success();
            }else{
                return Msg.fail();
            }
        }else{
            return Msg.fail();
        }
    }

    @Override
    public Msg getGoodsByEquipmentInfo(String startTime, String endTime, List<Integer> fieldList, Integer userId) {
        // 必须要传入用户ID
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);
        if (ToolUtil.isEmpty(checkUser)) {
            return Msg.fail().add("va_msg", "用户不存在");
        }
        if (CollectionUtils.isEmpty(fieldList)) {

            fieldList = null;
        }

        Map<String,Object> goodsVOList = this.goodsMapper.getGoodsByEquipmentInfo(userId,startTime, endTime, fieldList);

        return Msg.success().add("goodsVOList", goodsVOList);
    }




    /**
     * 购买商品结算
     * @param equipmentId     设备id
     * @param trailsJsonStr   购物车信息 json   {货道号，数量}
     * @return
     */
    public Msg updateBuyCommodity(String equipmentId, String trailsJsonStr) throws Exception {

        Equipment equipment = new Equipment();
        equipment.setEquipmentId(equipmentId);
        Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);
        if (ToolUtil.isEmpty(selectEquipment) || ToolUtil.isEmpty(selectEquipment.getEquipmentUserId())) {
            return Msg.setFailMsg("该设备无商户注册!!");
        }
        if (selectEquipment.getEquipmentUseCondition() == 1 ) {
            return Msg.setFailMsg("该设备当前不可用");
        }
        if (selectEquipment.getEquipmentState().equals("2")) {
            return Msg.setFailMsg("该设备处于离线状态");
        }

        //商户订单号
        String outTradeNoStr = WXPayUtil.onlineOrderMerchantNumber();
        //货道信息map集合
        Map<String,Integer> trailsMap;
        //总价
        Double total = 0.00;
        //保存要添加的货道商品信息
        List<OrderBuy> orderBuys = new ArrayList<OrderBuy>();

        if (ToolUtil.isNotEmpty(equipmentId) && ToolUtil.isNotEmpty(trailsJsonStr)) {
            //json字符串转换成map集合(key:货道id,value:数量)
            //trailsMap = (Map<String, Integer>) JSONObject.parse(trailsJsonStr);
            //处理字符串按照购买顺序出货
            trailsJsonStr = trailsJsonStr.replace("{", "");
            trailsJsonStr = trailsJsonStr.replace("}", "");
            trailsJsonStr = trailsJsonStr.replace("[", "");
            trailsJsonStr = trailsJsonStr.replace("]", "");
            trailsJsonStr = trailsJsonStr.replace("\"", "");
            //trailsJsonStr = trailsJsonStr.replace("\"", "");
        }else {
            return Msg.setFailMsg("传入信息为空");
        }

        String[] trailsMsg = trailsJsonStr.split(",");

        for (String trailsOne:trailsMsg) {
            String[] trailsOrNumber = trailsOne.split(":");

            //查询货道信息
            Trails trails = new Trails();
            trails.setTrailsId(Integer.parseInt(trailsOrNumber[0]));
            Trails selectTrails = this.trailsMapper.selectByPrimaryKeySelective(trails);
            if (ToolUtil.isEmpty(selectTrails)) {
                return Msg.fail().add("msg", "货道"+trailsOrNumber[0]+"不存在!");
                //continue;
            }
            //查询货道的商品信息
            Goods goods = new Goods();
            goods.setGoodsId(selectTrails.getTrailsGoodsId());
            Goods selectGoods = this.goodsMapper.selectByPrimaryKeySelective(goods);
            if (ToolUtil.isEmpty(selectGoods)) {
                return Msg.fail().add("msg", trailsOrNumber[0]+"货道商品不存在!");
                //continue;
            }
            //判断货道库存是否满足出货条件
            if (Integer.parseInt(trailsOrNumber[1]) > selectTrails.getTrailsGoodsStock()) {
                return Msg.fail().add("msg", trailsOrNumber[0]+"货道商品库存不足!");
                //continue;
            }
            //计算总金额
            total = BigDecimalUtils.add(total, BigDecimalUtils.mul(selectGoods.getGoodsPrice(), Integer.parseInt(trailsOrNumber[1])));

            //每个商品添加一条记录
            for (int i = 0; i < Integer.parseInt(trailsOrNumber[1]); i++) {
                //保存货道商品信息
                OrderBuy orderBuy = new OrderBuy();
                orderBuy.setOrderBuyGoodsId(selectGoods.getGoodsId());
                orderBuy.setOrderBuyGoodsName(selectGoods.getGoodsName());
                orderBuy.setOrderBuyGoodsPicture(selectGoods.getGoodsPicture());
                orderBuy.setOrderBuyGoodsPrice(selectGoods.getGoodsPrice());
                orderBuy.setOrderBuyTrailsId(selectTrails.getTrailsId());
                orderBuy.setOrderBuyTrailsNumber(selectTrails.getTrailsNumber());
                orderBuy.setOrderBuyType(0);//(0)
                orderBuy.setOrderBuyPosition(selectTrails.getTrailsPosition());
                orderBuy.setOrderBuyState(0);//未出货
                orderBuy.setOrderBuyRefund(0);//未退款
                orderBuy.setOrderBuyTrailsType(selectTrails.getTrailsType());
                orderBuy.setOrderBuyCaseId(selectTrails.getTrailsCaseId());
                orderBuys.add(orderBuy);
            }

        }

        // 添加线上订单(返回订单id)
        Integer result = this.iOnlineOrderService.insertOnlineOrder(outTradeNoStr, equipmentId, total);

        if (result != 0) {
            //添加该订单的货道商品信息到数据库
            for (OrderBuy order : orderBuys) {
                order.setOrderBuyParentId(result);

                this.orderBuyMapper.insertSelective(order);
            }

            return Msg.success().add("onlineOrderId", result);
        }else {
            return Msg.setFailMsg("生成订单失败!");
        }

    }


    /**
     * 根据设备id查询商品(Android)
     * @param equipmentId
     * @return
     */
    public Msg selectGoodsByEquipmentId(String equipmentId) {

        if (ToolUtil.isNotEmpty(equipmentId)) {

            List<Object> boxes = new ArrayList<Object>();

            //根据设备id查询设备信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isNotEmpty(selectEquipment)) {

                //查询设备机箱信息
                List<Trails> trailsCaseList = this.trailsMapper.selectCaseGroupBy(equipmentId);

                if (ToolUtil.isNotEmpty(trailsCaseList)) {

                    for (Trails caseNumber: trailsCaseList) {

                        List<Object> caseList = new ArrayList<Object>();
                        EquipmentTypeBoxes equipmentTypeBoxes = new EquipmentTypeBoxes();

                        //查询改机箱的层信息
                        List<Trails> trailsRiseList = this.trailsMapper.selectRiseGroupBy(caseNumber.getTrailsCaseId(), equipmentId);

                        if (ToolUtil.isNotEmpty(trailsRiseList)) {

                            for (Trails riseNumber: trailsRiseList) {

                                //查询该层的货道信息
                                Trails trails = new Trails();
                                trails.setTrailsRiseId(riseNumber.getTrailsRiseId());
                                trails.setTrailsCaseId(caseNumber.getTrailsCaseId());
                                trails.setTrailsEquipmentId(equipmentId);
                                List<Trails> trailsList = this.trailsMapper.selectByExampleSelective(trails);

                                if (ToolUtil.isNotEmpty(trailsList)) {

                                    for (Trails forTrails: trailsList) {

                                        if (ToolUtil.isEmpty(forTrails.getTrailsGoodsId())) {
                                            continue;
                                        }

                                        //查询该货道的商品信息
                                        Goods goods = new Goods();
                                        goods.setGoodsId(forTrails.getTrailsGoodsId());
                                        Goods selectGoods = this.goodsMapper.selectByPrimary(goods);

                                        if (ToolUtil.isNotEmpty(selectGoods)) {

                                            //查询完所有信息，保存所有的信息
                                            TrailsGoodsShow trailsGoodsShow = new TrailsGoodsShow();
                                            trailsGoodsShow.setTrailsId(forTrails.getTrailsId());
                                            trailsGoodsShow.setTrailsPosition(forTrails.getTrailsPosition());
                                            trailsGoodsShow.setGoodsId(selectGoods.getGoodsId());
                                            trailsGoodsShow.setGoodsName(selectGoods.getGoodsName());
                                            trailsGoodsShow.setGoodsPicture(selectGoods.getGoodsPicture());
                                            trailsGoodsShow.setGoodsPrice(selectGoods.getGoodsPrice());
                                            trailsGoodsShow.setGoodsRemark(selectGoods.getGoodsRemark());
                                            trailsGoodsShow.setGoodsStock(forTrails.getTrailsGoodsStock());
                                            trailsGoodsShow.setTrailsGoodsCapacity(forTrails.getTrailsGoodsCapacity());
                                            trailsGoodsShow.setTrailsAlarm(forTrails.getTrailsAlarm());
                                            trailsGoodsShow.setTrailsCaseNumber(caseNumber.getTrailsCaseId());

                                            Dict dict = new Dict();
                                            dict.setId(forTrails.getTrailsType());
                                            Dict selectDict = this.dictMapper.selectByPrimaryKeySelective(dict);

                                            Integer trailsType = selectDict.getNum();
                                            if (trailsType == 1) {
                                                trailsGoodsShow.setTrailsType("A");
                                            }else if (trailsType == 2) {
                                                trailsGoodsShow.setTrailsType("C");
                                            }else if (trailsType == 3) {
                                                trailsGoodsShow.setTrailsType("B");
                                            }else{
                                                trailsGoodsShow.setTrailsType("");
                                            }

                                            caseList.add(trailsGoodsShow);
                                        }
                                    }
                                }

                            }
                        }
                        equipmentTypeBoxes.setBoxNum(caseNumber.getTrailsCaseId());
                        equipmentTypeBoxes.setGoodsList(caseList);
                        boxes.add(equipmentTypeBoxes);
                    }
                }

            }else {
                return Msg.fail().add("msg", "该设备不存在");
            }

            return Msg.success().add("boxes", boxes);
        }else {
            return Msg.fail();
        }
    }


    @Override
    public Msg getGoodsStatisticsByUser(String startTime,Integer[] integers, String endTime, Integer fieldId, Integer userId, String condition,Integer pageNum) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 必须要传入查询时间
        if (ToolUtil.isEmpty(startTime)) {
            return Msg.fail().add("va_msg", "请输入起始时间");
        }
        if (ToolUtil.isEmpty(endTime)) {
            return Msg.fail().add("va_msg", "请输入截止时间");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(checkUser)) {
            return Msg.fail().add("va_msg", "用户不存在");
        }
        Equipment equipment = new Equipment();
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "未找到对应用户");
        }else{
            equipment.setEquipmentUserId(userId);
        }
        Integer pageStart = (pageNum - 1)*10;
        List<Equipment> list = new ArrayList<Equipment>();
        List<Integer> del_ids = new ArrayList<Integer>();
        if(ToolUtil.isNotEmpty(fieldId)){
            if(fieldId == 0){
                List<List<Equipment>> lists = new ArrayList<List<Equipment>>();
               /* Field field1 = new Field();
                field1.setFieldUserId(userId);
                if(ToolUtil.isNotEmpty(condition)){
                    field1.setFieldName(condition);
                }
                field1.setNum(pageStart);*/
                //所有场地(场地名称)
                List<Field> fieldList = fieldMapper.selectByFiExample(condition,pageStart,integers);
                for(Field field:fieldList){
                    del_ids.add(field.getFieldId());
                    equipment.setEquipmentFieldId(field.getFieldId());
                    //(设备id)
                    List<Equipment> equipmentList = equipmentMapper.selectByExample(equipment);
                    lists.add(equipmentList);
                }
                for(int j = 0;j < lists.size(); j++){
                    list.addAll(lists.get(j));
                }
            }else{
                Field f = new Field();
                f.setFieldId(fieldId);
                if(ToolUtil.isNotEmpty(condition)){
                    f.setFieldName(condition);
                }
                Field field = fieldMapper.selectByPrimary(f);
                if(ToolUtil.isNotEmpty(field)){
                    del_ids.add(field.getFieldId());
                    equipment.setEquipmentFieldId(field.getFieldId());
                    list = equipmentMapper.selectByExample(equipment);
                }
            }
        }
        List<GoodsStatistics> equipmentLists = new ArrayList<GoodsStatistics>();
        if(ToolUtil.isNotEmpty(list)    ){
        for(Equipment e:list){
            for(Integer f:del_ids){
                if(e.getEquipmentFieldId().equals(f)){
                    GoodsStatistics goodsStatistics = new GoodsStatistics();
                    Field fi = new Field();
                    fi.setFieldId(f);
                    Field fds = fieldMapper.selectByPrimary(fi);
                    goodsStatistics.setFieldName(fds.getFieldName());
                    goodsStatistics.setFieldId(fds.getFieldId());

                    List<GoodsStatisticsFieldListByOne> listones = new ArrayList<>();
                    GoodsStatisticsFieldListByOne byOne = new GoodsStatisticsFieldListByOne();

                    byOne.setEquipmentId(e.getEquipmentId());
                    byOne.setEquipmentNumber(e.getEquipmentNumber());

                    //库存
                    int stock = 0;
                    if(ToolUtil.isNotEmpty(e.getEquipmentModelId())){
                        Trails trails = new Trails();
                        trails.setTrailsEquipmentId(e.getEquipmentId());
                        List<Trails> trailsList = trailsMapper.selectByExample(trails);
                        for(Trails t:trailsList){
                            stock += t.getTrailsGoodsStock();
                        }
                    }
                    byOne.setGoodsStock(stock);
                    //线上收益
                    Double onlineMoney = onlineOrderMapper.selectByEquipment(e.getEquipmentId(),userId,startTime,endTime);
                    Double refundMoney = orderBuyMapper.selectByEquipment(e.getEquipmentId(),userId,startTime,endTime);
                    byOne.setOnlineMoney(BigDecimalUtils.sub(onlineMoney,refundMoney));
                    //线下收益
                    Double underlineMoney = onlineOrderMapper.selectUnderByEquipment(e.getEquipmentId(),userId,startTime,endTime);
                    byOne.setUnderlineMoney(underlineMoney);

                    List<GoodsConsume> goodsConsumes = goodsConsumeMapper.selectByEquipment(e.getEquipmentId(),userId,startTime,endTime);
                    byOne.setGoodsConsumeNum(goodsConsumes.size());

                    /*List<GoodsConsumeList> consumeLists = new ArrayList<>();
                    for(GoodsConsume goodsConsume:goodsConsumes){
                        GoodsConsumeList consumeList = new GoodsConsumeList();
                        Goods g = new Goods();
                        g.setGoodsId(goodsConsume.getGoodsConsumeGoodsId());
                        Goods goods = goodsMapper.selectByPrimary(g);
                        consumeList.setGoodsName(goods.getGoodsName());
                        consumeList.setGoodsPrice(goods.getGoodsPrice());
                        consumeList.setTime(goodsConsume.getGoodsConsumeTime());
                        consumeLists.add(consumeList);
                    }
                    byOne.setConsumeLists(consumeLists);*/

                    listones.add(byOne);
                    goodsStatistics.setList(listones);
                    if(equipmentLists.size() > 0){
                        int cli = 0;
                        for(int i = 0;i < equipmentLists.size();i++){
                            if(equipmentLists.get(i).getFieldName().equals(goodsStatistics.getFieldName())){
                                equipmentLists.get(i).getList().addAll(listones);
                                cli += 1;
                            }
                        }
                        if(cli == 0){
                            equipmentLists.add(goodsStatistics);
                        }
                    }else{
                        equipmentLists.add(goodsStatistics);
                    }
                }
            }
        }
        }
        for(int i = 0;i < equipmentLists.size();i++){
            Integer sm = 0;
            for(int j = 0;j < equipmentLists.get(i).getList().size();j++){
                //商品总消耗数
                sm += equipmentLists.get(i).getList().get(j).getGoodsConsumeNum();
            }
            equipmentLists.get(i).setGoodsConsumeNum(sm);
        }
        return Msg.success().add("equipmentLists", equipmentLists);
    }

    @Override
    public Msg getGoodsByEquipment(Integer userId, String startTime, String endTime, String equipmentId, Integer pageNum) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 必须要传入查询时间
        if (ToolUtil.isEmpty(startTime)) {
            return Msg.fail().add("va_msg", "请输入起始时间");
        }
        if (ToolUtil.isEmpty(endTime)) {
            return Msg.fail().add("va_msg", "请输入截止时间");
        }
        Integer pageStart = (pageNum - 1) * 10;
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(checkUser)) {

            return Msg.fail().add("va_msg", "用户不存在");
        }
        List<OnlineOrder> onlineOrders = onlineOrderMapper.selectByEquipmentTime(
                userId,equipmentId,startTime,endTime,pageStart);

        List<GoodsOrderVO> goodsOrderVOList = new ArrayList<>();
        for(OnlineOrder order:onlineOrders){
            GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
            //订单号
            goodsOrderVO.setOnlineOrderDealNumber(order.getOnlineOrderDealNumber());
            goodsOrderVO.setTime(order.getOnlineOrderTime());

            Map<String,Object> mapCount = goodsConsumeMapper.selectCountByEquipment(order.getOnlineOrderId());

            goodsOrderVO.setMoneyTotal(Double.parseDouble(mapCount.get("goodsAmount").toString()));
            GoodsConsume goodsConsume = new GoodsConsume();
            goodsConsume.setGoodsOrderId(order.getOnlineOrderId());
                //商品
            List<GoodsDetailsVO> goodsDetailList = new ArrayList<>();
                //商品消耗表
            List<GoodsConsume> goodsConsumes = goodsConsumeMapper.selectByExample(goodsConsume);
            for(int i = 0;i < goodsConsumes.size();i++){
                if(goodsDetailList.size() > 0){
                    for(int j = 0;j < goodsDetailList.size();j++){
                        if(goodsConsumes.get(i).getGoodsConsumeGoodsId().equals(goodsDetailList.get(j).getGoodsId())){
                            goodsDetailList.get(j).setGoodsNumber(goodsDetailList.get(j).getGoodsNumber() + 1);
                        }else{
                            int x = 1;
                            int y = 1;
                            for(int k = 0;k < goodsDetailList.size();k++){
                                Goods go = new Goods();
                                go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                                Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                                if(goodsDetailList.get(k).getGoodsId().equals(goods.getGoodsId())){
                                    y += 1;
                                    break;
                                }else{
                                    x += 1;
                                }
                            }
                            if(x > 1 && y <= 1){
                                GoodsDetailsVO goodsDetailsVO = new GoodsDetailsVO();
                                Goods go = new Goods();
                                go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                                Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                                goodsDetailsVO.setGoodsId(goods.getGoodsId());
                                goodsDetailsVO.setGoodsName(goods.getGoodsName());
                                goodsDetailsVO.setGoodsPicture(goods.getGoodsPicture());
                                goodsDetailsVO.setGoodsPrice(goodsConsumes.get(i).getGoodsConsumePrice());
                                goodsDetailsVO.setGoodsNumber(1);
                                goodsDetailList.add(goodsDetailsVO);
                                break;
                            }
                        }
                    }
                }else{
                    GoodsDetailsVO goodsDetailsVO = new GoodsDetailsVO();
                    Goods go = new Goods();
                    go.setGoodsId(goodsConsumes.get(i).getGoodsConsumeGoodsId());
                    Goods goods = goodsMapper.selectByPrimaryKeySelective(go);
                    goodsDetailsVO.setGoodsId(goods.getGoodsId());
                    goodsDetailsVO.setGoodsName(goods.getGoodsName());
                    goodsDetailsVO.setGoodsPicture(goods.getGoodsPicture());
                    goodsDetailsVO.setGoodsPrice(goodsConsumes.get(i).getGoodsConsumePrice());
                    goodsDetailsVO.setGoodsNumber(1);
                    goodsDetailList.add(goodsDetailsVO);
                }

            }
            goodsOrderVO.setList(goodsDetailList);
            goodsOrderVOList.add(goodsOrderVO);

        }
        /*Paging paging = Paging.pagination(goodsOrderVOList.size(),10,pageNum);
        int fromIndex = paging.getQueryIndex();
        int toIndex = 0;
        if (fromIndex + paging.getPageSize() >= goodsOrderVOList.size()){
            toIndex = goodsOrderVOList.size();
        }else {
            toIndex = fromIndex +  paging.getPageSize();
        }
        if (fromIndex > toIndex){
            return Msg.success().add("goodsOrder",Collections.EMPTY_LIST);
        }*/

        return Msg.success().add("goodsOrder",goodsOrderVOList);
    }

    @Override
    public Msg getOnlineByEquipment(Integer userId, String startTime, String endTime, String equipmentId, Integer pageNum) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(checkUser)) {
            return Msg.fail().add("va_msg", "用户不存在");
        }
        pageNum = (pageNum - 1) * 10;
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("equipmentId", equipmentId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pageNum", pageNum);
        List<OnlineOrderVo> onlineMoneyList = onlineOrderMapper.getOnlineByEquipment(map);
        for(OnlineOrderVo onlineOrderVO:onlineMoneyList){
            if (onlineOrderVO.getOnlineOrderMoney() == null) {

                onlineOrderVO.setOnlineOrderMoney(0D);
            }
        }
        return Msg.success().add("onlineList",onlineMoneyList);
    }

    @Override
    public Msg getUnderlineByEquipment(Integer userId, String startTime, String endTime, String equipmentId, Integer pageNum) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(checkUser)) {

            return Msg.fail().add("va_msg", "用户不存在");
        }
        pageNum = (pageNum - 1) * 10;
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("equipmentId", equipmentId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pageNum", pageNum);
        List<UnderlineOrderVo> list = onlineOrderMapper.selectUnlineByEquipment(map);
        return Msg.success().add("underOrder",list);
    }

    @Override
    public List<Goods> selectByExample(Goods goods) {
        return goodsMapper.selectByExample(goods);
    }

    @Override
    public Msg getGoodsConsume(Integer userId, String startTime, String endTime,Integer[] integers) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("msg", "用户信息不能为空");
        }
        GoodsConsumeVo goodsConsumeVo = goodsConsumeMapper.selectCountByTime(userId,startTime,endTime,integers);
        if(ToolUtil.isEmpty(goodsConsumeVo.getCountMoney())){
            goodsConsumeVo.setCountMoney(0D);
        }
        if(ToolUtil.isEmpty(goodsConsumeVo.getCountSum())){
            goodsConsumeVo.setCountSum(0);
        }
        return Msg.success().add("goodsConsume",goodsConsumeVo);
    }

    @Override
    public Msg getGoodsConsumeList(Integer userId,Integer[] integers, String startTime, String endTime,Integer pageNum) {
        if(ToolUtil.isEmpty(userId)){
            return Msg.fail().add("va_msg", "用户信息不能为空");
        }
        // 必须要传入查询时间
        if (ToolUtil.isEmpty(startTime)) {
            return Msg.fail().add("va_msg", "请输入起始时间");
        }
        if (ToolUtil.isEmpty(endTime)) {
            return Msg.fail().add("va_msg", "请输入截止时间");
        }
        Integer pageStart = (pageNum - 1) * 10;
        // 首先校验用户是否存在
        User user = new User();
        user.setUserId(userId);

        User checkUser = this.userMapper.selectByPrimaryKey(user);

        if (ToolUtil.isEmpty(checkUser)) {

            return Msg.fail().add("va_msg", "用户不存在");
        }
        List<OnlineOrder> onlineOrders = onlineOrderMapper.selectByFieldTime(userId,integers,startTime,endTime,pageStart);
        List<GoodsConsumeOrder> list = new ArrayList<>();
        for(int i = 0;i < onlineOrders.size();i++){
            GoodsConsumeOrder goodsConsumeOrder = new GoodsConsumeOrder();
            Equipment e = new Equipment();
            e.setEquipmentId(onlineOrders.get(i).getOnlineOrderEquipmentId());
            Equipment equipment = equipmentMapper.selectByPrimary(e);
            //商品个数
            GoodsConsume goodsConsume = new GoodsConsume();
            goodsConsume.setGoodsOrderId(onlineOrders.get(i).getOnlineOrderId());

           /* List<GoodsConsume> consumeList = goodsConsumeMapper.selectByExample(goodsConsume);
            if(consumeList.size() > 0){*/

            //时间
            goodsConsumeOrder.setTime(onlineOrders.get(i).getOnlineOrderTime());
            //设备id 设备编号
            goodsConsumeOrder.setEquipmentId(equipment.getEquipmentId());
            goodsConsumeOrder.setEquipmentNumber(equipment.getEquipmentNumber());
            //订单id
            goodsConsumeOrder.setOnlineOrderId(onlineOrders.get(i).getOnlineOrderId());
            //价钱
            Map<String,Object> mapCount = goodsConsumeMapper.selectCountByEquipment(onlineOrders.get(i).getOnlineOrderId());
            goodsConsumeOrder.setGoodsCount(Double.parseDouble(mapCount.get("goodsAmount").toString()));
            //商品个数
            goodsConsumeOrder.setGoodsNum(Integer.parseInt(mapCount.get("countSum").toString()));
            Field f = new Field();
            f.setFieldId(onlineOrders.get(i).getOnlineOrderFileldId());
            Field field = fieldMapper.selectByPrimary(f);
            goodsConsumeOrder.setFieldName(field.getFieldName());
            list.add(goodsConsumeOrder);
            /*}*/
        }
        return Msg.success().add("goodsOrder",list);
    }

    @Override
    public Msg getGoodsConsumeDetails(Integer onlineOrderId) {
        //订单
        OnlineOrder o = new OnlineOrder();
        o.setOnlineOrderId(onlineOrderId);
        OnlineOrder onlineOrder = onlineOrderMapper.selectByPrimaryKeySelective(o);
        //设备
        Equipment e = new Equipment();
        e.setEquipmentId(onlineOrder.getOnlineOrderEquipmentId());
        Equipment equipment = equipmentMapper.selectByPrimary(e);

        Customer c = new Customer();
        c.setCustomerOpenId(onlineOrder.getOnlineOrderOpenid());
        Customer customer = customerService.selectByPrimary(c);

        OrderBuy ob = new OrderBuy();
        ob.setOrderBuyParentId(onlineOrderId);
        List<OrderBuy> orderBuyList = orderBuyMapper.selectByExampleSelective(ob);

        if(orderBuyList.size() > 0){
            GoodsConsumeOrder goodsConsumeOrder = new GoodsConsumeOrder();
            goodsConsumeOrder.setCustomerName(customer.getCustomerName());
            goodsConsumeOrder.setCustomerPhoto(customer.getCustomerPhoto());
            goodsConsumeOrder.setEquipmentId(equipment.getEquipmentId());
            goodsConsumeOrder.setEquipmentNumber(equipment.getEquipmentNumber());
            goodsConsumeOrder.setTime(onlineOrder.getOnlineOrderTime());
            //订单出货状态
            goodsConsumeOrder.setOnlineShipmentState(onlineOrder.getOnlineOrderShipment());

            goodsConsumeOrder.setOnlineOrderId(onlineOrderId);
            //价钱
            if(ToolUtil.isEmpty(onlineOrder.getOnlineOrderMoney())){
                goodsConsumeOrder.setGoodsCount(0D);
            }else{
                goodsConsumeOrder.setGoodsCount(onlineOrder.getOnlineOrderMoney());
            }
            Field f = new Field();
            f.setFieldId(onlineOrder.getOnlineOrderFileldId());
            Field field = fieldMapper.selectByPrimary(f);
            goodsConsumeOrder.setFieldName(field.getFieldName());

            Double money = 0D;
            List<OrderBuyVO> orderBuyVOS = new ArrayList<>();
            for(OrderBuy orderBuy:orderBuyList){
                OrderBuyVO orderBuyVO = new OrderBuyVO();
                String riseTrails = orderBuy.getOrderBuyTrailsNumber();
                String[] str = riseTrails.split("-");
                //层
                orderBuyVO.setOrderBuyRise(str[0]);
                //货道号
                orderBuyVO.setOrderBuyTrails(str[1]);
                orderBuyVO.setOrderBuyCaseId(orderBuy.getOrderBuyCaseId());

                /*EquipmentTypeCase equipmentTypeCase = new EquipmentTypeCase();
                equipmentTypeCase.setEquipmentCaseId(orderBuy.getOrderBuyCaseId());
                //机箱
                EquipmentTypeCase typeCase = equipmentTypeCaseMapper.selectByPrimaryKeySelective(equipmentTypeCase);*/
                orderBuyVO.setEquipmentCaseNumber(orderBuy.getOrderBuyCaseId());
                orderBuyVO.setOrderBuyId(orderBuy.getOrderBuyId());
                orderBuyVO.setGoodsPrice(orderBuy.getOrderBuyGoodsPrice());
                orderBuyVO.setGoodsName(orderBuy.getOrderBuyGoodsName());
                orderBuyVO.setGoodsPicture(orderBuy.getOrderBuyGoodsPicture());
                //出货状态
                orderBuyVO.setOrderBuyState(orderBuy.getOrderBuyState());
                //退款状态
                orderBuyVO.setOrderBuyRefund(orderBuy.getOrderBuyRefund());
                int x = 0;
                if(orderBuy.getOrderBuyState() == 2 && orderBuy.getOrderBuyRefund() == 0){
                    x += 1;
                }else if(orderBuy.getOrderBuyState() == 2 && orderBuy.getOrderBuyRefund() == 2){
                    x +=1;
                }else if(orderBuy.getOrderBuyState() == 0 && orderBuy.getOrderBuyRefund() == 0){
                    x +=1;
                }else if(orderBuy.getOrderBuyState() == 0 && orderBuy.getOrderBuyRefund() == 2){
                    x +=1;
                }

                if(x > 0){
                    money = BigDecimalUtils.add(money,orderBuy.getOrderBuyGoodsPrice());
                }
                orderBuyVOS.add(orderBuyVO);
            }
            Map<String,Object> map = goodsConsumeMapper.selectConsumeByOrderId(onlineOrderId);
            goodsConsumeOrder.setGoodsNum(Integer.parseInt(map.get("goodsCount").toString()));
            goodsConsumeOrder.setGoodsConsumeMoney(Double.parseDouble(map.get("goodsConsumePrice").toString()));
            goodsConsumeOrder.setOrderBuyVOList(orderBuyVOS);
            goodsConsumeOrder.setRefundMoney(money);
            return Msg.success().add("goodsConsume",goodsConsumeOrder);
        }
        return Msg.fail();
    }


    /**
     * 查询商品列表(无屏售货机购买商品)
     * @return
     */
    public Msg selectShopCartGoodsByEquipmentId(String equipmentId) {

        if (ToolUtil.isNotEmpty(equipmentId)) {

            List<Object> goodsList = new ArrayList<Object>();

            //根据设备id查询设备信息
            Equipment equipment = new Equipment();
            equipment.setEquipmentId(equipmentId);
            Equipment selectEquipment = this.equipmentMapper.selectByPrimary(equipment);

            if (ToolUtil.isNotEmpty(selectEquipment)) {

                //查询该设备的机箱分组
                List<Trails> trailsCaseList = this.trailsMapper.selectCaseGroupBy(equipmentId);

                if (ToolUtil.isNotEmpty(trailsCaseList)) {

                    for (Trails caseNumber: trailsCaseList) {

                        List<Object> caseList = new ArrayList<Object>();

                        //查询该设备改机箱的层分组
                        List<Trails> trailsRiseList = this.trailsMapper.selectRiseGroupBy(caseNumber.getTrailsCaseId(), equipmentId);

                        if (ToolUtil.isNotEmpty(trailsRiseList)) {

                            for (Trails riseNumber: trailsRiseList) {

                                List<Object> trailsGoodsShowList = new ArrayList<Object>();

                                //查询该层的货道信息
                                Trails trails = new Trails();
                                trails.setTrailsRiseId(riseNumber.getTrailsRiseId());
                                trails.setTrailsCaseId(caseNumber.getTrailsCaseId());
                                trails.setTrailsEquipmentId(equipmentId);
                                List<Trails> trailsList = this.trailsMapper.selectByExampleSelective(trails);

                                if (ToolUtil.isNotEmpty(trailsList)) {

                                    for (Trails forTrails: trailsList) {

                                        //查询完所有信息，保存所有的信息
                                        TrailsGoodsShow trailsGoodsShow = new TrailsGoodsShow();
                                        trailsGoodsShow.setTrailsId(forTrails.getTrailsId());
                                        trailsGoodsShow.setTrailsPosition(forTrails.getTrailsNumber());
                                        trailsGoodsShow.setTrailsGoodsCapacity(forTrails.getTrailsGoodsCapacity());
                                        trailsGoodsShow.setTrailsAlarm(forTrails.getTrailsAlarm());
                                        if (ToolUtil.isNotEmpty(forTrails.getTrailsType())) {
                                            trailsGoodsShow.setTrailsType(forTrails.getTrailsType().toString());
                                        }
                                        trailsGoodsShow.setGoodsStock(forTrails.getTrailsGoodsStock());
                                        if (ToolUtil.isNotEmpty(forTrails.getTrailsGoodsId())) {
                                            //查询该货道的商品信息
                                            Goods goods = new Goods();
                                            goods.setGoodsId(forTrails.getTrailsGoodsId());
                                            Goods selectGoods = this.goodsMapper.selectByPrimary(goods);

                                            if (ToolUtil.isNotEmpty(selectGoods)) {
                                                trailsGoodsShow.setGoodsId(selectGoods.getGoodsId());
                                                trailsGoodsShow.setGoodsName(selectGoods.getGoodsName());
                                                trailsGoodsShow.setGoodsPicture(selectGoods.getGoodsPicture());
                                                trailsGoodsShow.setGoodsPrice(selectGoods.getGoodsPrice());
                                                trailsGoodsShow.setGoodsRemark(selectGoods.getGoodsRemark());
                                            }
                                        }
                                        trailsGoodsShowList.add(trailsGoodsShow);
                                    }
                                }
                                //保存每层的信息
                                EquipmentTypeRiseResult equipmentTypeRiseResult = new EquipmentTypeRiseResult();
                                equipmentTypeRiseResult.setRiseNumber(riseNumber.getTrailsRiseId().toString());
                                equipmentTypeRiseResult.setRiseAllList(trailsGoodsShowList);
                                caseList.add(equipmentTypeRiseResult);
                            }
                        }
                        //保存每个箱柜的信息
                        EquipmentTypeCaseResult equipmentTypeCaseResult = new EquipmentTypeCaseResult();
                        equipmentTypeCaseResult.setCaseNumber(caseNumber.getTrailsCaseId());
                        equipmentTypeCaseResult.setCaseList(caseList);
                        goodsList.add(equipmentTypeCaseResult);
                    }
                }

            }else {
                return Msg.fail().add("msg", "该设备不存在");
            }

            Integer equipmentType = 2;//离线
            if (selectEquipment.getEquipmentState().equals("1")) {
                //如果设备是在线的，返回信息
                equipmentType = 1;
            }
            return Msg.success().add("goodsList", goodsList).add("equipmentType", equipmentType);
        }else {
            return Msg.fail();
        }
    }



    /**
     * 特殊需求，购买结算商品前输入病区与床号
     * @param equipmentId              设备id
     * @param trailsJsonStr            商品jsonStr
     * @param areaNumber               病区
     * @param bedNumber                床号
     * @return
     */
    public Msg insertMedicineOrder(String equipmentId, String trailsJsonStr, String areaNumber, String bedNumber) {
        if (ToolUtil.isEmpty(equipmentId)) {
            return Msg.fail().add("msg", "设备不存在");
        }
        if (ToolUtil.isEmpty(trailsJsonStr)) {
            return Msg.fail().add("msg", "未购买商品");
        }
        if (ToolUtil.isEmpty(areaNumber)) {
            return Msg.fail().add("msg", "请选择病区");
        }
        if (ToolUtil.isEmpty(bedNumber)) {
            return Msg.fail().add("msg", "请选择床号");
        }

        Medicine medicine = new Medicine();
        medicine.setMedicineArea(areaNumber);
        try {
            medicine.setMedicineBedNumber(Integer.parseInt(bedNumber));
        }catch (Exception e) {
            return Msg.fail().add("msg", "床号输入有误");
        }
        medicine.setMedicineCreateTime(DateUtil.getTime());
        medicine.setMedicineEquipmentId(equipmentId);
        medicine.setMedicineStatus(0);

        Msg orderMsg = Msg.fail();
        //生成订单
        try {
            orderMsg = this.updateBuyCommodity(equipmentId, trailsJsonStr);
            if (ToolUtil.isNotEmpty(orderMsg) && ToolUtil.isNotEmpty(orderMsg.getExtend().get("onlineOrderId"))) {
                medicine.setMedicineOrderId(Integer.parseInt(orderMsg.getExtend().get("onlineOrderId").toString()));

                //查询订单信息
                OnlineOrder onlineOrder = new OnlineOrder();
                onlineOrder.setOnlineOrderId(Integer.parseInt(orderMsg.getExtend().get("onlineOrderId").toString()));
                OnlineOrder selectOnlineOrder = this.onlineOrderMapper.selectByPrimaryKeySelective(onlineOrder);
                if (ToolUtil.isNotEmpty(selectOnlineOrder)) {
                    medicine.setMedicineUserId(selectOnlineOrder.getOnlineOrderUserId());
                    medicine.setMedicineMoney(selectOnlineOrder.getOnlineOrderMoney());
                }else {
                    return Msg.fail();
                }
            }else {
                return Msg.fail().add("msg", "订单生成失败");
            }
        } catch (Exception e) {
            Msg.fail().add("msg", "订单生成失败");
        }

        this.medicineMapper.insertSelective(medicine);

        return orderMsg;
    }



    /**
     * 查询商品销售排行（不分设备，根据用户）
     * @param userId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public Msg selectGoodsRanking(Integer userId, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        if (ToolUtil.isEmpty(userId)) {
            return Msg.fail().add("msg", "未获取登录信息");
        }
        if (ToolUtil.isEmpty(startTime) || ToolUtil.isEmpty(endTime)) {
            return Msg.fail().add("msg", "请输入日期区间");
        }

        //分页
        PageHelper.startPage(pageNum,pageSize);
        List<GoodsRanking> goodsRankings = this.goodsConsumeMapper.selectGoodsRanking(userId, startTime, endTime);
        PageInfo page = new PageInfo(goodsRankings, 5);
//        return Msg.success().add("pageInfo", page);

        return Msg.success().add("goodsRankings", goodsRankings).add("pageNum", pageNum).add("pageSize", pageSize).add("pages", page.getPages()).add("pageTotal", page.getTotal());
    }

}
